package cn.iocoder.mall.order.application.controller.admins;

import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.common.utils.common.api.vo.Result;
import cn.iocoder.common.utils.common.system.query.QueryGenerator;
import cn.iocoder.common.utils.common.util.ObjectUtils;
import cn.iocoder.common.utils.common.util.oConvertUtils;
import cn.iocoder.mall.order.api.OrderService;
import cn.iocoder.mall.order.api.bo.*;
import cn.iocoder.mall.order.api.dto.*;
import cn.iocoder.mall.order.application.convert.OrderConvertAPP;
import cn.iocoder.mall.order.application.convert.OrderDeliveryConvert;
import cn.iocoder.mall.order.application.convert.OrderReturnConvert;
import cn.iocoder.mall.order.application.po.admin.IOrderPageQueryPO;
import cn.iocoder.mall.order.application.po.admin.OrderDeliverPO;
import cn.iocoder.mall.order.application.po.admin.OrderItemUpdatePO;
import cn.iocoder.mall.order.application.po.admin.OrderLogisticsPO;
import cn.iocoder.mall.order.application.vo.AdminsOrdersPageVO;
import cn.iocoder.mall.order.application.vo.OrderVO;
import cn.iocoder.mall.order.biz.service.OrderAdminService;
import cn.iocoder.mall.shop.api.ShopService;
import cn.iocoder.mall.shop.api.pojo.ShopDTO;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

/**
 * 订单API(admins)
 *
 * @author Sin
 * @time 2019-03-24 10:22
 */
@RestController
@RequestMapping("/admin/order/")
@Api(value = "订单 API(admins)")
public class AdminsOrderController {

    @Reference(validation = "true", version = "${dubbo.provider.OrderService.version}")
    private OrderService orderService;
    @Autowired
    private OrderAdminService orderAdminService;
    @Reference(validation = "true", version = "${dubbo.consumer.ShopService.version}")
    ShopService shopService;

    @GetMapping("orderDetails")
    public Result<?> getOrderDetails(@Validated IOrderPageQueryPO orderPageQueryVO,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        orderPageQueryVO.setPageNo(pageNo);
        orderPageQueryVO.setPageSize(pageSize);
        OrderQueryDTO orderQueryDTO = OrderConvertAPP.INSTANCE.convert(orderPageQueryVO);
        CommonResult<OrderPageBO>  bo= orderService.getOrders(orderQueryDTO);
        List<OrderBO> list=bo.getData().getOrders();
        return Result.ok(list);
    }

    @GetMapping("page")
    @ApiOperation("订单列表")
    public Result<?> getOrderPage(@Validated IOrderPageQueryPO orderPageQueryVO) {

        OrderQueryDTO orderQueryDTO = OrderConvertAPP.INSTANCE.convert(orderPageQueryVO);
        CommonResult<OrderPageBO>  bo= orderService.getOrderPage(orderQueryDTO);
        List<OrderBO> list=bo.getData().getOrders();
        Page<OrderBO> page=new Page<>();
        page.setRecords(list);
        page.setTotal(bo.getData().getTotal());
        return Result.ok(page);
    }

    @GetMapping("order_items")
    @ApiOperation("订单列表")
    public CommonResult<List<OrderItemBO>> getOrderItems(@RequestParam("orderId") Long orderId) {
        return orderService.getOrderItems(orderId);
    }

    @GetMapping("order_recipient_info")
    @ApiOperation("订单收件人信息")
    public CommonResult<OrderRecipientBO> getOrderRecipientBO(@RequestParam("orderId") Long orderId) {
        return orderService.getOrderRecipientBO(orderId);
    }

    @PostMapping("order_deliver")
    @ApiOperation("订单发货")
    public CommonResult<OrderRecipientBO> orderDeliver(@RequestBody @Validated OrderDeliverPO orderDeliverPO) {
        return orderService.orderDelivery(OrderDeliveryConvert.INSTANCE.convert(orderDeliverPO));
    }

    @PutMapping("update_remark")
    @ApiOperation("更新-更新订单备注")
    public CommonResult updateRemark(@RequestParam("orderId") Long orderId,
                                     @RequestParam("remark") String remark) {
        return orderService.updateOrderRemake(orderId, remark);
    }

    @PutMapping("cancel_order")
    @ApiOperation("取消订单")
    public CommonResult cancelOrder(
            @RequestParam("orderId") Long orderId,
            @RequestParam("reasons") Integer reasons,
            @RequestParam(value = "otherReasons", required = false) String otherReasons) {
        return orderService.cancelOrder(orderId, reasons, otherReasons);
    }

    @PutMapping("order_item/update_pay_amount")
    @ApiOperation("更新-订单item实付金额")
    public CommonResult updateOrderItemPayAmount(@RequestParam("orderId") Long orderId,
                                                 @RequestParam("orderItemId") Integer orderItemId,
                                                 @RequestParam("payAmount") Integer payAmount) {
        return orderService.updateOrderItemPayAmount(orderId, orderItemId, payAmount);
    }

    @PutMapping("order_item/update")
    @ApiOperation("更新-订单item")
    public CommonResult updateOrderItem(@RequestBody @Validated OrderItemUpdatePO orderItemUpdateVO) {
        OrderItemUpdateDTO dto = OrderConvertAPP.INSTANCE.convert(orderItemUpdateVO);
        return orderService.updateOrderItem(dto);
    }

    @PutMapping("logistics/update")
    @ApiOperation("更新-订单物流")
    public CommonResult updateLogistics(@RequestBody @Validated OrderLogisticsPO orderLogisticsVO) {
        OrderLogisticsUpdateDTO dto = OrderConvertAPP.INSTANCE.convert(orderLogisticsVO);
        return orderService.updateLogistics(dto);
    }
    @GetMapping("seller/page")
    @ApiOperation(value = "商户端 店铺订单的分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value = "订单编号", example = "参考 CouponTemplateTypeEnum 枚举"),
            @ApiImplicitParam(name = "status", value = "状态", example = "参考 CouponTemplateStatusEnum 枚举"),
            @ApiImplicitParam(name = "pageNo", value = "页码，从 1 开始", example = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, example = "10"),
    })
    public Result<?> sellerPage(@RequestParam(value = "orderNo", required = false) String orderNo,
                                @RequestParam(value = "status", required = false) Integer status,
                                @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){
        List<ShopDTO> data = shopService.getListOfStores("7081ce121f69ab1d130747a39ddbaa0c").getData();
        List<String> shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());
        OrdersPageBO result=orderService.getSellerPage(new OrdersPageDTO()
                .setStatus(status).setOrderNo(orderNo).setPageNo(pageNo)
                .setPageSize(pageSize).setShopIds(shopIds));
        CommonResult<List<ShopDTO>> shopNames= shopService.getShopInfoById(shopIds);
        IPage page=new Page<>();
        AdminsOrdersPageVO vo= OrderReturnConvert.INSTANCE.convertPage(result);
        page.setTotal(vo.getTotal());
        page.setSize(pageSize);
        page.setRecords(vo.getList().stream()
                .map(a-> ObjectUtils.copyObject(a,OrdersPageDTO.class)
                    .setShopName(shopNames.getData().stream()
                        .filter(shopDTO -> shopDTO.getId().equals(a.getShopId()))
                            .map(ShopDTO::getShopName)
                        .findFirst().orElse(""))).collect(Collectors.toList()));
        System.out.println(page);
        return Result.ok(page);

    }
    /**l
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
//        // Step.1 组装查询条件
        QueryWrapper<OrderDTO> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                OrderDTO order = JSON.parseObject(deString, OrderDTO.class);
                queryWrapper = QueryGenerator.initQueryWrapper(order, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(request);

//        //Step.2 AutoPoi 导出Excel

        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<ShopDTO> data = shopService.getListOfStores("7081ce121f69ab1d130747a39ddbaa0c").getData();
        List<String> shopIds = data.stream().map(ShopDTO::getId).collect(Collectors.toList());
        List<OrderDTO> pageList=orderAdminService.autoList(shopIds);
        CommonResult<List<ShopDTO>> shopNames= shopService.getShopInfoById(shopIds);
        mv.addObject(NormalExcelConstants.FILE_NAME, "商户订单列表");
        mv.addObject(NormalExcelConstants.CLASS, OrderVO.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商户-订单列表数据", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList.stream().map(a->ObjectUtils.copyObject(a,OrderVO.class)
                .setShopName(shopNames.getData().stream().filter(shopDTO -> shopDTO.getId().equals(a.getShopId()))
                        .map(ShopDTO::getShopName)
                        .findFirst().orElse(""))).collect(Collectors.toList()));
        return mv;
    }
}
